package com.sparrows.pirates.controller.modes;

import java.util.ArrayList;

import com.sparrows.pirates.model.CrewMember;
import com.sparrows.pirates.model.Player;

/**
 * Implementation of the RPG battle system.
 * @author krummer
 *
 */
public class RpgBattle {
	public Player challenger; 
	public Player defender;	//challanger will almost always be the human player.
	
	private ArrayList<CrewMember> turnList;
	public CrewMember currentCrewMember; 
	public Player currentPlayer;
	
	public RpgBattle(Player challenger, Player defender) {
		this.challenger = challenger;
		this.defender = defender;
		this.turnList = new ArrayList<CrewMember>();
		this.makeTurnOrder();
		this.endTurn();
	}
	
	/**
	 * has to be called by interface, needs the ability slot and target as argument.
	 */
	public void makeTurn(int ability, CrewMember target) {
		this.currentCrewMember.abilities.get(ability).execute(target);
		this.endTurn();
	}
	
	/**
	 * Has to be called by interface, needs ability slot and target player.
	 * Use this for abilities that affect a whole crew.
	 * @param ability the slot index of the ability.
	 * @param player the affected player.
	 */
	public void makeTurn(int ability, Player player) {
		for(CrewMember c: player.getCrew()) {
			this.currentCrewMember.abilities.get(ability).execute(c);
		}
		this.endTurn();
	}
	
	/**
	 * Sets to next player and crew member.
	 */
	private void endTurn(){
		//check for stuff in order.
		this.refreshTurnOrder();
		
		CrewMember tmp = this.turnList.get(0);
		
		if(this.currentCrewMember == null) {
			this.currentCrewMember = tmp;
		} else {			
			//remove from front and add to end again.
			this.turnList.remove(tmp);
			this.turnList.add(tmp);
		}
		
		//set player based on crew.
		if(this.challenger.getCrew().contains(tmp)) {
			this.currentPlayer = challenger;
		} else {
			this.currentPlayer = defender;
		}
	}
	
	/**
	 * removes dead crew from the turn order.
	 */
	private void refreshTurnOrder() {
		for(CrewMember c: this.turnList) {
			if(c.health <= 0) this.turnList.remove(c);
		}
		this.turnList.trimToSize();
	}
	
	/**
	 * adds all crew members to the turnList and sorts the list.
	 */
	private void makeTurnOrder() {
		this.turnList.addAll(this.challenger.getCrew());
		this.turnList.addAll(this.defender.getCrew());
		
		//the deckhands attack first.
		//TODO: sort the list.	
	}
}
